package com.sgu6.sgu6_machine.ui.fragment.set;

import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.linheimx.app.library.adapter.DefaultValueAdapter;
import com.linheimx.app.library.charts.LineChart;
import com.linheimx.app.library.data.Entry;
import com.linheimx.app.library.data.Line;
import com.linheimx.app.library.data.Lines;
import com.linheimx.app.library.model.XAxis;
import com.linheimx.app.library.model.YAxis;
import com.sgu6.middleware.enums.MachineCmdEnum;
import com.sgu6.middleware.util.HexUtil;
import com.sgu6.serialport.manager.SerialPortManager;
import com.sgu6.sgu6_machine.R;
import com.sgu6.sgu6_machine.base.BaseF;
import com.sgu6.sgu6_machine.db.DBManager;
import com.sgu6.sgu6_machine.dto.ChargeDto;
import com.sgu6.sgu6_machine.dto.EletricDto;
import com.sgu6.sgu6_machine.dto.PowerDto;
import com.sgu6.sgu6_machine.dto.VoltageDto;
import com.sgu6.sgu6_machine.event.PowerEvent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 电机设置
 */
public class PowerF extends BaseF {

    @BindView(R.id.chart_v)
    LineChart chartV;
    @BindView(R.id.chart_a)
    LineChart chartA;
    @BindView(R.id.chart_p)
    LineChart chartP;
    @BindView(R.id.chart_c)
    LineChart chartC;

    Line lineV = new Line();
    Line lineA = new Line();
    Line lineP = new Line();
    Line lineC = new Line();
    List<Entry> entryV = new ArrayList<>();
    List<Entry> entryA = new ArrayList<>();
    List<Entry> entryP = new ArrayList<>();
    List<Entry> entryC = new ArrayList<>();
    Lines linesV = new Lines();
    Lines linesA = new Lines();
    Lines linesP = new Lines();
    Lines linesC = new Lines();

    public static PowerF newInstance() {
        return new PowerF();
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_power, container, false);
        unbinder = ButterKnife.bind(this, v);

        initUI();

        return v;
    }

    public void initUI() {
        initData();
        initCharts();
    }

    public void initData(){
        try {
            List<VoltageDto> voltageDtos = DBManager.getInstance(requireContext()).queryVoltage();
            entryV.add(new Entry(0,0));
            for (int i = 0; i < voltageDtos.size(); i++) {
                entryV.add(new Entry(i+1,voltageDtos.get(i).getVoltage()));
            }

            List<EletricDto> eletricDtos = DBManager.getInstance(requireContext()).queryEletric();
            entryA.add(new Entry(0,0));
            for (int i = 0; i < eletricDtos.size(); i++) {
                entryA.add(new Entry(i+1,eletricDtos.get(i).getEletric()));
            }

            List<PowerDto> powerDtos = DBManager.getInstance(requireContext()).queryPower();
            entryP.add(new Entry(0,0));
            for (int i = 0; i < powerDtos.size(); i++) {
                entryP.add(new Entry(i+1,powerDtos.get(i).getPower()));
            }

            List<ChargeDto> chargeDtos = DBManager.getInstance(requireContext()).queryCharge();
            entryC.add(new Entry(0,0));
            for (int i = 0; i < chargeDtos.size(); i++) {
                entryC.add(new Entry(i+1,chargeDtos.get(i).getCharge()));
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void initCharts() {
        // step1: 设置x,y轴
        XAxis xv = chartV.get_XAxis();
        xv.set_unit("单位：分");
        xv.setLabelTextSize(22);
        xv.set_ValueAdapter(new DefaultValueAdapter(0));

        YAxis yv = chartV.get_YAxis();
//        yv.set_unit("单位：m");
        yv.set_unit("单位：V");
        yv.setLabelTextSize(22);
//        yv.set_ValueAdapter(new DefaultValueAdapter(0));// 默认精度到小数点后2位,现在修改为3位精度
        // step2: 为一条数据线添加数据

        lineV.setEntries(entryV);
        lineV.setCircleR(2);
        lineV.setLineColor(Color.RED);
        linesV.addLine(lineV);
        chartV.setLines(linesV);

        // step1: 设置x,y轴
        XAxis xa = chartA.get_XAxis();
        xa.set_unit("单位：分");
        xa.setLabelTextSize(22);
        xa.set_ValueAdapter(new DefaultValueAdapter(0));

        YAxis ya = chartA.get_YAxis();
//        yv.set_unit("单位：m");
        ya.set_unit("单位：A");
        ya.setLabelTextSize(22);
//        yv.set_ValueAdapter(new DefaultValueAdapter(0));// 默认精度到小数点后2位,现在修改为3位精度
        // step2: 为一条数据线添加数据

        lineA.setEntries(entryA);
        lineA.setCircleR(2);
        lineA.setLineColor(Color.RED);
        linesA.addLine(lineA);
        chartA.setLines(linesA);

        // step1: 设置x,y轴
        XAxis xp = chartP.get_XAxis();
        xp.set_unit("单位：分");
        xp.setLabelTextSize(22);
        xp.set_ValueAdapter(new DefaultValueAdapter(0));

        YAxis yp = chartP.get_YAxis();
        yp.set_unit("单位：W");
        yp.setLabelTextSize(22);
//        yv.set_ValueAdapter(new DefaultValueAdapter(0));// 默认精度到小数点后2位,现在修改为3位精度
        // step2: 为一条数据线添加数据

        lineP.setEntries(entryP);
        lineP.setCircleR(2);
        lineP.setLineColor(Color.RED);
        linesP.addLine(lineP);
        chartP.setLines(linesP);

        // step1: 设置x,y轴
        XAxis xc = chartC.get_XAxis();
        xc.set_unit("单位：分");
        xc.setLabelTextSize(22);
        xc.set_ValueAdapter(new DefaultValueAdapter(0));

        YAxis yc = chartC.get_YAxis();
        yc.set_unit("单位：Kwh");
        yc.setLabelTextSize(22);
//        yv.set_ValueAdapter(new DefaultValueAdapter(0));// 默认精度到小数点后2位,现在修改为3位精度
        // step2: 为一条数据线添加数据


        lineC.setEntries(entryC);
        lineC.setCircleR(2);
        lineC.setLineColor(Color.RED);
        linesC.addLine(lineC);
        chartC.setLines(linesC);


//        // step3: 将数据放到 lineChart上
//        lines.addLine(horLine);
//        lines.addLine(verLine);
//        chart.setLines(lines);

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onPowerEvent(PowerEvent event) {
        if (event.type == 1) {//电压
            double value = getValue(event.cmd);
            entryV.add(new Entry(entryV.size(), value));
            lineV.setEntries(entryV);
            chartV.notifyDataChanged();
            chartV.invalidate();
        } else if (event.type == 2) { //电流
            double value = getValue(event.cmd);
            entryA.add(new Entry(entryA.size(), value));
            lineA.setEntries(entryA);
            chartA.notifyDataChanged();
            chartA.invalidate();
        } else if (event.type == 3) { //功率
            double value = getValue(event.cmd);
            entryP.add(new Entry(entryP.size(), value));
            lineP.setEntries(entryP);
            chartP.notifyDataChanged();
            chartP.invalidate();
        } else {//电量
            double value = getValue(event.cmd);
            entryC.add(new Entry(entryC.size(), value));
            lineC.setEntries(entryC);
            chartC.notifyDataChanged();
            chartC.invalidate();
        }
    }

    public double getValue(byte[] cmd) {
        byte[] v = new byte[4];
        System.arraycopy(cmd, 6, v, 0, 4);
        int value = HexUtil.byteToInt2(v);
        v = null;
        return value * 0.0001 * 100 / 100;
    }

    @Override
    public void onStart() {
        super.onStart();
        if (!EventBus.getDefault().isRegistered(this)){
            EventBus.getDefault().register(this);
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        EventBus.getDefault().unregister(this);
    }


    @OnClick({R.id.btn_voltage, R.id.btn_electric, R.id.btn_charge, R.id.btn_power})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_voltage:
                SerialPortManager.getInstance().sendBytes(HexUtil.HexString2Bytes(MachineCmdEnum.电压.code()));
                break;
            case R.id.btn_electric:
                SerialPortManager.getInstance().sendBytes(HexUtil.HexString2Bytes(MachineCmdEnum.电流.code()));
                break;
            case R.id.btn_charge:
                SerialPortManager.getInstance().sendBytes(HexUtil.HexString2Bytes(MachineCmdEnum.电量.code()));
                break;
            case R.id.btn_power:
                SerialPortManager.getInstance().sendBytes(HexUtil.HexString2Bytes(MachineCmdEnum.功率.code()));
                break;
//            case R.id.btn_power_1:
//                SerialPortManager.getInstance().sendBytes(HexUtil.HexString2Bytes(MachineCmdEnum.功率因素.code()));
//                break;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}
